#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <unistd.h>

#include "buram_armeabi-v7a.h"
#include "buram_armeabi-v7a_ioctl.h"

static int fd;
static int is_open = 0;

int Get_Ram(struct ram_dev *dev, unsigned int id)
{
	int ret;
	void *pio;
	unsigned long offset;
	struct mem_req req;
	pid_t pid;

	if (is_open == 0) {
		fd = open(IO_MEM_NODE, O_RDWR);
		if (fd < 0) {
			perror("open");
			return -1;
		}
		is_open = 1;
	}

        pid = getpid();

        ret = ioctl(fd, REG_PWR_DOWN, &pid);
        if (ret < 0) {
                perror("ioctl");
                return -1;
        }

	req.id = id;
	ret = ioctl(fd, GET_RAM_DATA, &req);
	if (ret < 0) {
		perror("ioctl");
		dev->start_addr = NULL;
		dev->block_length = 0;
		return -1;
	}

	dev->block_length = req.info.size;
	offset = req.info.addr;
	pio = mmap(NULL, dev->block_length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset);

	if ((int) pio == -1) {
		pio = NULL;
		perror("mmap");
		close(fd);
		is_open = 0;
		dev->start_addr = NULL;
		dev->block_length = 0;
		return -1;
	}

	dev->start_addr = pio;

	return 0;
}
